package org.peoplesearch.pseindexer.peopleretrieval;

import org.peoplesearch.vk.utils.SerializableUser;

import java.io.*;
import java.util.Iterator;

public class FileIterator implements Iterator<SerializableUser> {

    private final String dataDir;

    public FileIterator(String dataDir) {
        this.dataDir = dataDir;
    }

    public static void main(String[] args) {
        FileIterator fileIterator = new FileIterator("/data/temp2");
        int i = 0;
        while (fileIterator.hasNext()) {
            SerializableUser user = fileIterator.next();
            System.out.println((i++) + " " + user.user.first_name + " " + user.user.last_name + " " + user.user.uid +" " + user.user.relation);
        }
    }

    private int currentFileNumber = 0;
    ObjectInputStream bufferedReader;


    SerializableUser current;
    Boolean last_value = null;
    int recordNumber;

    public boolean hasNext() {
        if (last_value != null) {
            return last_value;
        }
        if (recordNumber == 0) {
            bufferedReader = null;
        }
        try {
            while ((bufferedReader == null) || ((--recordNumber) < -1000) || ((current = (SerializableUser) bufferedReader.readObject()) == null)) {
                currentFileNumber++;
                File currentFile = new File(dataDir + "/" + currentFileNumber);
                if (currentFile.exists()) {
                    bufferedReader = new ObjectInputStream(new FileInputStream(currentFile));
                    recordNumber = (Integer) bufferedReader.readObject();
                } else {
                    last_value = false;
                    return false;
                }
            }
            last_value = true;
            return true;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public SerializableUser next() {
        try {
            last_value = null;
            return current;
        } finally {
            hasNext();
        }
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }

}
